package com.jtjrenren.android.taxi.driver.core.dutyon;


import android.content.Intent;
import android.os.CountDownTimer;

import com.jtjrenren.android.taxi.driver.Constants;
import com.jtjrenren.android.taxi.driver.base.BaseApplication;
import com.jtjrenren.android.taxi.driver.bean.DriverInfo;
import com.jtjrenren.android.taxi.driver.bean.OrderDesc;
import com.jtjrenren.android.taxi.driver.bean.OrderQD;
import com.jtjrenren.android.taxi.driver.bean.control.CmdOtherDutyOnResponse;
import com.jtjrenren.android.taxi.driver.bean.control.CmdPasPayResultResponse;
import com.jtjrenren.android.taxi.driver.bean.control.CmdQdResultResponse;
import com.jtjrenren.android.taxi.driver.bean.control.CmdXDResponse;
import com.jtjrenren.android.taxi.driver.bean.control.CmdZxQxDdResponse;
import com.jtjrenren.android.taxi.driver.bean.event.ControlCenterEvent;
import com.jtjrenren.android.taxi.driver.bean.event.DriverIncomeEvent;
import com.jtjrenren.android.taxi.driver.bean.event.ExitEvent;
import com.jtjrenren.android.taxi.driver.bean.event.OrderNotFinishEvent;
import com.jtjrenren.android.taxi.driver.bean.event.YydListEvent;
import com.jtjrenren.android.taxi.driver.bean.event.YydTxEvent;
import com.jtjrenren.android.taxi.driver.manger.AppManger;
import com.jtjrenren.android.taxi.driver.manger.TtsManger;
import com.jtjrenren.android.taxi.driver.manger.push.cmd.ControlCmd;
import com.jtjrenren.android.taxi.driver.utils.GsonUtils;
import com.library.mvp.presenter.MvpBasePresenter;
import com.library.utils.AppUtils;
import com.library.utils.LogUtil;
import com.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/26.
 */

public class DutyOnPresenterImpl extends MvpBasePresenter<DutyOnView, DutyOnInterctor> implements DutyOnPresenter {
    private static final int ACCEPT_TYPE_ALL = 1;//接全部单
    private static final int ACCEPT_TYPE_SS = 2;//只接实时单
    private static final int REFRESH_TIMEDOWN_QD_COUNT = 60; //刷新抢单倒计时倒计时总时间 秒

    private int acceptType = ACCEPT_TYPE_ALL;
    private OrderQD currentOrderNO = null;
    private ArrayList<OrderQD> qdList = new ArrayList<>(); //下发的订单
    private List<OrderQD> tmpList = new ArrayList<>();
    private List<String> qds = new ArrayList<>();

    private CountDownTimer countDownTimer = null;

    private void stratCountDown(long count) {
        LogUtil.log("dutyon", "current_method_presenter--->stratCountDown");
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        countDownTimer = new CountDownTimer(count * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (currentOrderNO != null)
                    view.refreshQdDjs(millisUntilFinished / 1000 + "");
            }

            @Override
            public void onFinish() {
                closeCurOrder();
            }
        };
        countDownTimer.start();
    }

    private void stopCountDown() {
        LogUtil.log("dutyon", "current_method_presenter--->stopCountDown");
        if (countDownTimer != null)
            countDownTimer.cancel();
        countDownTimer = null;
    }

    public DutyOnPresenterImpl(DutyOnView view) {
        super(view);
    }


    @Override
    public void init() {
        LogUtil.log("dutyon", "current_method_presenter--->init");
        EventBus.getDefault().register(this);
        refreshSr();
    }

    @Override
    public void destory() {
        LogUtil.log("dutyon", "current_method_presenter--->destory");
        EventBus.getDefault().unregister(this);
        stopCountDown();

        if (qdList != null)
            qdList.clear();
        qdList = null;
    }


    @Override
    public DutyOnInterctor createInteractor() {
        return new DutyOnInterctorImpl();
    }

    @Override
    public void xB() {
        LogUtil.log("dutyon", "current_method_presenter--->xB");
        AppManger.getInstance().driverOffDuty();
        view.showXBView();
    }

    @Override
    public void changeQdType() {
        LogUtil.log("dutyon", "current_method_presenter--->changeQdType");
        String desc = "全部";
        if (acceptType == ACCEPT_TYPE_ALL) {
            acceptType = ACCEPT_TYPE_SS;
            desc = "实时";
        } else
            acceptType = ACCEPT_TYPE_ALL;

        view.refreshQdType(desc);
    }

    @Override
    public void qd() {
        LogUtil.log("dutyon", "current_method_presenter--->qd");
        if (currentOrderNO == null)
            return;

        qds.add(currentOrderNO.getXdResponse().getOrderID());

        String qdCmd = ControlCmd.getQdCmd(currentOrderNO.getXdResponse().getOrderID());
        AppManger.getInstance().sendMsg(qdCmd);
        TtsManger.getInstance().stop();
        TtsManger.getInstance().speak("抢单中，请稍候");

        int pos = qdList.indexOf(currentOrderNO);
        if (pos >= 0)
            qdList.get(pos).setQd(true);

        stopCountDown();
        view.rereshQdStatus("抢单中");

        refreshQDList();
    }

    @Override
    public void getNotFinishOrder() {
        LogUtil.log("dutyon", "current_method_presenter--->getNotFinishOrder");
        DriverInfo driver = AppManger.getInstance().driver;
        if (driver == null)
            return;
        String carNo = "";
        String driverID = driver.getWorkNo();
        interactor.getNotFinishOrder(carNo, driverID);
    }

    @Override
    public void refreshCurrOrder(OrderQD orderQD) {
        LogUtil.log("dutyon", "current_method_presenter--->refreshCurrOrder");
        stopCountDown();
        currentOrderNO = orderQD;

        CmdXDResponse xdResponse = orderQD.getXdResponse();

        TtsManger.getInstance().stop();
        if (xdResponse.getOrderType() == Constants.TYPE_ORDER_YY) {
            TtsManger.getInstance().speak("预约订单");
            TtsManger.getInstance().speak(xdResponse.getDate());
        } else if (xdResponse.getOrderType() == Constants.TYPE_ORDER_JS)
            TtsManger.getInstance().speak("实时订单");

        OrderDesc orderDesc = GsonUtils.getObj(xdResponse.getOrderAddrDesc(), OrderDesc.class);
        if (orderDesc == null)
            return;

        TtsManger.getInstance().speak(orderDesc.getDT() +
                "起点" + orderDesc.getFA() + "终点:" + orderDesc.getTA() + orderDesc.getSF() + orderDesc.getMe());

        view.refreshOrderView(xdResponse.getOrderType(), xdResponse.getDate(), orderDesc);

        if (!orderQD.isQd()) {
            int count_qddjs = REFRESH_TIMEDOWN_QD_COUNT - (int) (System.currentTimeMillis() - orderQD.getXdTime()) / 1000;
            LogUtil.log("order", "倒计时：" + count_qddjs);
            count_qddjs = count_qddjs > 0 ? count_qddjs : 0;
            stratCountDown(count_qddjs);
        } else {

            view.rereshQdStatus("抢单中");
        }
    }

    @Override
    public void closeCurOrder() {
        LogUtil.log("dutyon", "current_method_presenter--->closeCurOrder");
        delReceiveOrder(currentOrderNO);
        currentOrderNO = null;
        refreshQDList();
    }

    @Override
    public ArrayList<OrderQD> getQrderList() {
        LogUtil.log("dutyon", "current_method_presenter--->getQrderList");
        return qdList;
    }

    @Override
    public void getRefreshYYD() {
        LogUtil.log("dutyon", "current_method_presenter--->getRefreshYYD--->" + Thread.currentThread().toString());
        interactor.getYyd(AppManger.getInstance().driver.getWorkNo());
    }

    @Override
    public void refreshSr() {
        LogUtil.log("dutyon", "current_method_presenter--->refreshSr");
        interactor.refreshJtsr(AppManger.getInstance().driver.getWorkNo());
    }

    //刷新抢单的列表
    @Override
    public void refreshQDList() {
        LogUtil.log("dutyon", "current_method_presenter--->refreshQDList");
        if (qdList.size() == 0) {
            qdComplted();
            return;
        }
        //如果当前显示的订单不为null 但是抢单列表里边不存在 则这个是不存在的
        if (currentOrderNO != null && !qdList.contains(currentOrderNO))
            currentOrderNO = null;

        //将已经超时的订单清除,但是在抢单的保留
        int djs = 0;
        for (OrderQD info : qdList) {
            djs = REFRESH_TIMEDOWN_QD_COUNT - (int) (System.currentTimeMillis() - info.getXdTime()) / 1000;
            if (djs <= 0 && !info.isQd())
                tmpList.add(info);
        }
        delReceiveOrder(tmpList);
        tmpList.clear();

        //如果当前显示的订单为null，则将第一个订单进行显示(因为是列表，所以最后一个是最新的)
        if (currentOrderNO == null && qdList.size() > 0)
            refreshCurrOrder(qdList.get(qdList.size() - 1));

        //如果没有需要当前显示的订单而且订单列表都为空，则清空
        if (currentOrderNO != null)
            view.refreshOrderList();

        if (qdList.size() == 0)
            qdComplted();
    }

    @Subscribe
    public void handExitEvent(ExitEvent event) {
        LogUtil.log("dutyon", "current_method_presenter--->handExitEvent");
        view.finishAty();
    }

    @Subscribe
    public void handSrEvent(DriverIncomeEvent event) {
        LogUtil.log("dutyon", "current_method_presenter--->handSrEvent");
        if (event.getInfo() != null && !StringUtils.isEmpty(event.getInfo().getMsg().getIncome())) {
            view.refreshSr(event.getInfo().getMsg().getIncome());
        }
    }

    @Subscribe
    public void handYydListEvent(YydListEvent event) {
        LogUtil.log("dutyon", "current_method_presenter--->handYydListEvent");
        if (event.getApiYYDs() != null && event.getApiYYDs().size() > 0) {
            view.refreshYyd(event.getApiYYDs());
            view.refreshYYDCount(event.getApiYYDs().size());
        } else
            view.refreshYYDCount(0);
    }

    @Subscribe
    public void handNotFinishEvent(OrderNotFinishEvent event) {
        LogUtil.log("dutyon", "current_method_presenter--->handNotFinishEvent");
        if (event != null && !StringUtils.isEmpty(event.getOrderID()))
            view.qdSuccess(event.getOrderID());

    }

    //预约单提醒的通知
    @Subscribe
    public void handYydTx(YydTxEvent event) {
        LogUtil.log("dutyon", "current_method_presenter--->handYydTx");

    }

    @Subscribe
    public void handControlEvent(ControlCenterEvent event) {
        LogUtil.log("dutyon", "current_method_presenter--->handControlEvent");
        String action = event.getAction();
        LogUtil.log("order", "上班状态收到的订单消息:" + action + "-->" + event.getResponse().toString());
        if (Constants.ACTION_CONTROL_RESPONSE_XD.equals(action)) {
            receiveOrder(((CmdXDResponse) event.getResponse()));
        } else if (Constants.ACTION_CONTROL_RESPONSE_ZXQXDD.equals(action))
            cancleOrder((CmdZxQxDdResponse) event.getResponse());
        else if (Constants.ACTION_CONTROL_RESPONSE_QDRESULT.equals(action))
            qdResult((CmdQdResultResponse) event.getResponse());
        else if (Constants.ACTION_CONTROL_RESPONSE_PASPAYRESULT.equals(action))
            payResult(event);
        else if (Constants.ACTION_CONTROL_RESPONSE_OTHERDUTYON.equals(action)) {
            otherDutyOn((CmdOtherDutyOnResponse) event.getResponse());
        }
    }

    //其他设备登陆的消息
    private void otherDutyOn(CmdOtherDutyOnResponse response) {
        LogUtil.log("dutyon", "本账号在其他设备登陆");
        AppManger.getInstance().showTip(response.getDesc());
        if (response.getType().equals(CmdOtherDutyOnResponse.TYPE_EXIT)) {
            LogUtil.log("dutyon", "本账号在其他设备登陆===>" + "强制退出");
            AppManger.getInstance().driverExit();
            view.showLoginView();
        } else if (response.getType().equals(CmdOtherDutyOnResponse.TYPE_OFF)) {
            LogUtil.log("dutyon", "本账号在其他设备登陆===>" + "强制退出");
            xB();
        }
    }


    //支付结果的回复
    private void payResult(ControlCenterEvent event) {
        LogUtil.log("dutyon", "current_method_presenter--->payResult");
        TtsManger.getInstance().speak(((CmdPasPayResultResponse) event.getResponse()).getDesc());
        view.showPayResult(((CmdPasPayResultResponse) event.getResponse()).getOrderID());
        refreshSr();
    }

    //抢单完成
    private void qdComplted() {
        LogUtil.log("dutyon", "current_method_presenter--->qdComplted");
        if (countDownTimer != null)
            countDownTimer.cancel();
        view.stopCheckQdList();
        TtsManger.getInstance().stop();
        view.hideOrderWin();
        view.rereshQdStatus("接单中");
        qdList.clear();
        qds.clear();
    }

    //删除抢单信息
    private void delQd(String orderID) {
        LogUtil.log("dutyon", "current_method_presenter--->delQd");
        for (OrderQD info : qdList) {
            if (orderID.equals(info.getXdResponse().getOrderID())) {
                delReceiveOrder(info);
                break;
            }
        }
    }

    //抢单结果
    private void qdResult(CmdQdResultResponse cmdQdResultResponse) {
        LogUtil.log("dutyon", "current_method_presenter--->qdResult");
        TtsManger.getInstance().stop();

        if (cmdQdResultResponse.isQdSuccess()) {
            AppManger.getInstance().qdSuccess();
            TtsManger.getInstance().speak("抢单成功");

            qdComplted();

            view.qdSuccess(cmdQdResultResponse.getOrderID());
        } else {
            String orderID = cmdQdResultResponse.getOrderID();
            if (qds.indexOf(orderID) >= 0) {
                TtsManger.getInstance().stop();
                TtsManger.getInstance().speak("抢单失败");
            }
            refreshQDList();
            delQd(orderID);
        }
    }

    //取消订单的回复
    private void cancleOrder(CmdZxQxDdResponse zxQxDdResponse) {
        LogUtil.log("dutyon", "current_method_presenter--->cancleOrder");
        String orderID = zxQxDdResponse.getOrderSno();
        delQd(orderID);

        TtsManger.getInstance().stop();
        TtsManger.getInstance().speak("订单取消");
        refreshQDList();
    }

    //接受到订单
    private void receiveOrder(CmdXDResponse xdResponse) {
        LogUtil.log("dutyon", "current_method_presenter--->receiveOrder");
        if (acceptType == ACCEPT_TYPE_SS && xdResponse.getOrderType() == Constants.TYPE_ORDER_YY)
            return;

        if (AppUtils.isApplicationBroughtToBackground(BaseApplication.getInstance().getApplicationContext())) {
            LogUtil.log("order", "接单运行在后台");
            TtsManger.getInstance().speak("新订单通知");
            OrderDesc orderDesc = GsonUtils.getObj(xdResponse.getOrderAddrDesc(), OrderDesc.class);
            view.moveToFont(orderDesc.getFA() + "-->" + orderDesc.getTA());
        }
        if (!(AppManger.getInstance().currentActivity instanceof WorkDutyOnActivity)) {
            LogUtil.log("order", "接单没有运行在栈顶");
            AppManger.getInstance().currentActivity.startActivity(new Intent(AppManger.getInstance().currentActivity, WorkDutyOnActivity.class));
        }

        view.startCheckQdList();
        currentOrderNO = null;
        OrderQD orderQD = new OrderQD(System.currentTimeMillis(), xdResponse);
        addNewReceiveOrder(orderQD);
        refreshQDList();
    }

    //添加抢单实体
    private void addNewReceiveOrder(OrderQD orderQD) {
        LogUtil.log("dutyon", "current_method_presenter--->addNewReceiveOrder");
        synchronized (qdList) {
            qdList.add(orderQD);
        }
    }

    //删除抢单实体
    private void delReceiveOrder(OrderQD orderQD) {
        LogUtil.log("dutyon", "current_method_presenter--->delReceiveOrder");
        synchronized (qdList) {
            qdList.remove(orderQD);
        }
    }

    //删除抢单实体
    private void delReceiveOrder(List<OrderQD> list) {
        LogUtil.log("dutyon", "current_method_presenter--->delReceiveOrder");
        synchronized (qdList) {
            qdList.removeAll(list);
        }
    }
}
